package fun.coding.leetcode;

import java.util.ArrayList;
import java.util.List;

public class ZigZagConversion {

	public static void main(String[] args) {
		ZigZagConversion ins = new ZigZagConversion();
		System.out.println(ins.convert("PAYPALISHIRING", 3));
		System.out.println(ins.convert("AB", 1));
	}
	
	public String convert(String s, int nRows) {
		if (s == null || s.length() == 0 || nRows <= 0) return "";
		
		if (nRows == 1) return s;
		
		int l = s.length();
		List<StringBuilder> buckets = new ArrayList<StringBuilder>();
		
		for (int i = 0; i < nRows; i++) {
			buckets.add(new StringBuilder());
		}
		
		int i = 0; 
		int index = 0;
		boolean fromLeftToRight = true;
		while (i < l) {
			char c = s.charAt(i);
			
			if (fromLeftToRight) {
				if (index == nRows - 1) {
					fromLeftToRight = false;
					buckets.get(index).append(c);
					index--;
				} else {
					buckets.get(index).append(c);
					index++;
				}
			} else {
				if (index == 0) {
					fromLeftToRight = true;
					buckets.get(index).append(c);
					index++;
				} else {
					buckets.get(index).append(c);
					index--;
				}
			}
			i++;
		}
		
		String res = "";
		for (StringBuilder sb : buckets) {
			res += sb.toString();
		}
		
		return res;
	}
}
